﻿using LD.Host;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;

namespace LD.Tool
{
    [Tool(FrmParam = "ToolVariableJudgeFrm", Text = "全局变量判断", ToolType = ToolEnum.Other)]
    public class ToolVariableJudge : BaseTool
    {
        public override OpResult Execute(TB_Tool model)
        {
            stopwatch.Start();
            isSuccess = false;
            if (!string.IsNullOrEmpty(model.Param))
            {
                JObject obj = JObject.Parse(model.Param);

                string name = obj["name"].ToString();
                string value = obj["value"].ToString();
                object newValue = null;

                try
                {
                    string dataTypeVal = Cache.Var.Where(x => x.Name == name).FirstOrDefault().DataType;
                    DataType dataType = (DataType)Enum.Parse(typeof(DataType), dataTypeVal);

                    try
                    {
                        switch (dataType)
                        {
                            case DataType.Int:
                                newValue = Convert.ToInt32(value);
                                break;
                            case DataType.Float:
                                newValue = float.Parse(value);
                                break;
                            case DataType.String:
                                newValue = value;
                                break;
                            case DataType.Double:
                                newValue = Convert.ToDouble(value);
                                break;
                            case DataType.Bool:
                                newValue = Convert.ToBoolean(value);
                                break;
                            default:
                                throw new Exception();
                        }
                    }
                    catch (Exception)
                    {
                        throw new Exception($"值【{value}】无法被强制转换为类型【{dataType}】");
                    }

                    isSuccess = false;

                    var val = Cache.Var.Where(p => p.Name == name).FirstOrDefault();
                    if (val != null && val.Val.Equals(newValue))
                        isSuccess = true;
                }
                catch (Exception ex)
                {
                    isSuccess = false;
                    Log4.Error(ex);
                }
            }
            stopwatch.Stop();
            return new OpResult() { IsSuccess = isSuccess, Message = "", ExecuteTime = stopwatch.ElapsedMilliseconds };
        }
    }
}
